# coding=utf8
from math import sqrt


class filter:
    def computeSimilarity(self, band, band2, userdata):
        avgs = {};
        for (key, rat) in userdata.items():
            avgs[key] = float(sum(rat.values())) / len(rat);

        num = 0  # 分子
        dem1 = 0  # 分母的第一部分
        dem2 = 0
        for (user, rat) in userdata.items():
            if band in rat and band2 in rat:
                avg = avgs[user];
                num += (rat[band] - avg) * (rat[band2] - avg);
                dem1 += pow((rat[band] - avg), 2);
                dem2 += pow((rat[band2]) - avg, 2);
        print num / (sqrt(dem1) * sqrt(dem2));
